package com.hbnu.serve;

import com.hbnu.dao.StudyRecordDAO;
import com.hbnu.entity.*;
import com.hbnu.service.*;
import com.hbnu.util.DBUtil;

import java.io.*;
import java.net.Socket;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ClientHandler extends Thread {
    private final Socket clientSocket;
    private final UserService userService = new UserService();
    private final WordService wordService = new WordService();
    private final SystemWordBookService systemBookService = new SystemWordBookService();
    private final UserWordBookService userBookService = new UserWordBookService();
    private User loginUser;

    public ClientHandler(Socket socket) {
        this.clientSocket = socket;
    }

    // 处理登录
    private void handleLogin(BufferedReader in, PrintWriter out) throws IOException {
        out.println("请输入用户名：");
        String username = in.readLine();
        out.println("请输入密码：");
        String password = in.readLine();

        try {
            loginUser = userService.login(username, password);
            out.println("登录成功！欢迎您，" + loginUser.getUsername() + "！");
        } catch (Exception e) {
            out.println("登录失败：" + e.getMessage());
        }
    }

    // 处理注册
    private void handleRegister(BufferedReader in, PrintWriter out) throws IOException {
        out.println("请输入用户名：");
        String username = in.readLine();
        if (username == null || username.trim().isEmpty()) {
            out.println("注册失败：用户名不能为空");
            return; // 回到初始选择界面
        }
        out.println("请输入密码：");
        String password = in.readLine();

        try {
            userService.register(username, password);
            out.println("注册成功，请登录！");
            handleLogin(in, out);
        } catch (Exception e) {
            out.println("注册失败：" + e.getMessage());
        }
    }

    // 主菜单循环
    private void mainMenuLoop(BufferedReader in, PrintWriter out) throws IOException {
        showMainMenu(out);

        String input;
        while ((input = in.readLine()) != null) {
            switch (input) {
                case "1":
                    handleSearchWord(in, out);
                    break;
                case "2":
                    handleSystemBooks(in, out);
                    break;
                case "3":
                    handleUserBooks(in, out);
                    break;
                case "4":
                    out.println("再见！");
                    return;
                default:
                    out.println("无效命令，请重新输入");
            }
            showMainMenu(out);
        }
    }

    // 显示主菜单
    private void showMainMenu(PrintWriter out) {
        out.println("\n=== 主菜单 ===");
        out.println("1. 查找单词（按字母）");
        out.println("2. 选择系统词书");
        out.println("3. 我的单词本");
        out.println("4. 退出系统");
        out.println("请输入选择(1-4)：");
    }

    // 处理单词查询
    private void handleSearchWord(BufferedReader in, PrintWriter out) throws IOException {
        out.println("请输入要查询的字母序列：");
        String letter = in.readLine();

        try {
            List<Word> words = wordService.searchWord(letter);
            out.println("\n=== 找到 " + words.size() + " 个单词 ===");
            for (int i = 0; i < words.size(); i++) {
                out.println("[" + (i + 1) + "] " + words.get(i));
                out.println("---------------------");
            }
        } catch (Exception e) {
            out.println("查询失败：" + e.getMessage());
        }
    }

    // 处理系统词书
    private void handleSystemBooks(BufferedReader in, PrintWriter out) throws IOException {
        try {
            List<SystemWordBook> books = systemBookService.getAllSystemBooks();
            out.println("\n=== 系统词书列表 ===");
            for (SystemWordBook book : books) {
                out.println(book);
                out.println("---------------------");
            }

            out.println("请输入要查看的词书ID（输入0返回）：");
            int bookId = Integer.parseInt(in.readLine());
            if (bookId == 0) return;

            List<Word> words = systemBookService.getWordsByBookId(bookId);
            out.println("\n=== 词书中的单词 ===");
            for (int i = 0; i < words.size(); i++) {
                out.println("[" + (i + 1) + "] " + words.get(i).getWord() + " - " + words.get(i).getDefinition());
            }
        } catch (Exception e) {
            out.println("操作失败：" + e.getMessage());
        }
    }

    // 处理用户自定义单词本
    private void handleUserBooks(BufferedReader in, PrintWriter out) throws IOException {
        out.println("\n=== 我的单词本操作 ===");
        out.println("1. 查看我的单词本");
        out.println("2. 创建新单词本");
        out.println("3. 向单词本添加单词");
        out.println("4. 查看单词本中的单词");
        out.println("0. 返回上一级");
        out.println("请选择：");

        String choice = in.readLine();
        switch (choice) {
            case "1":
                showUserBooks(out);
                break;
            case "2":
                createUserBook(in, out);
                break;
            case "3":
                addWordToUserBook(in, out);
                break;
            case "4":
                showWordsInUserBook(in, out);
                break;
            case "0":
                return;
            default:
                out.println("无效选择");
        }
    }

    // 显示用户单词本
    private void showUserBooks(PrintWriter out) {
        try {
            List<UserWordBook> books = userBookService.getUserWordBooks(loginUser.getId());
            out.println("\n=== 我的单词本 ===");
            for (UserWordBook book : books) {
                out.println(book);
                out.println("---------------------");
            }
        } catch (Exception e) {
            out.println("获取失败：" + e.getMessage());
        }
    }

    // 创建用户单词本
    private void createUserBook(BufferedReader in, PrintWriter out) throws IOException {
        out.println("请输入新单词本名称：");
        String bookName = in.readLine();

        try {
            userBookService.createWordBook(loginUser.getId(), bookName);
            out.println("单词本创建成功！");
        } catch (Exception e) {
            out.println("创建失败：" + e.getMessage());
        }
    }

    // 向单词本添加单词
    private void addWordToUserBook(BufferedReader in, PrintWriter out) throws IOException {
        out.println("请输入单词本ID：");
        int bookId = Integer.parseInt(in.readLine());
        out.println("请输入要添加的单词ID：");
        int wordId = Integer.parseInt(in.readLine());

        try {
            userBookService.addWordToBook(bookId, wordId);
            out.println("单词添加成功！");
        } catch (Exception e) {
            out.println("添加失败：" + e.getMessage());
        }
    }

    // 查看单词本中的单词
    private void showWordsInUserBook(BufferedReader in, PrintWriter out) throws IOException {
        out.println("请输入要查看的单词本ID：");
        int bookId = Integer.parseInt(in.readLine());

        try {
            List<Word> words = userBookService.getWordsFromBook(bookId,loginUser.getId());
            out.println("\n=== 单词本中的单词 ===");
            for (int i = 0; i < words.size(); i++) {
                out.println("[" + (i + 1) + "] " + words.get(i));
                out.println("---------------------");
            }
        } catch (Exception e) {
            out.println("获取失败：" + e.getMessage());
        }
    }




    @Override
    public void run() {
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream(),"UTF-8"));
             PrintWriter out = new PrintWriter(
                     new OutputStreamWriter(clientSocket.getOutputStream(),"UTF-8"), true)) {

            out.println("=== 欢迎使用背单词系统 ===");
            out.println("请选择操作：1-登录 2-注册");
            out.flush();
            String input;
            while ((input = in.readLine()) != null) {
                if ("1".equals(input)) {
                    handleLogin(in, out);
                    break;
                } else if ("2".equals(input)) {
                    handleRegister(in, out);
                    break;
                } else {
                    out.println("无效选择，请输入1或2");
                }
            }

            // 登录/注册成功后进入主菜单
            if (loginUser != null) {
                mainMenuLoop(in, out);
            }

        } catch (IOException e) {
            System.err.println("客户端处理异常：" + e.getMessage());
        } finally {
            try {
                clientSocket.close();
                System.out.println("客户端连接已关闭");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
    private void handleLearnNewWords(BufferedReader in, PrintWriter out) throws IOException {
        out.println("\n=== 学习新单词 ===");
        out.println("请选择词书类型：1-系统词书 2-我的单词本");
        String typeChoice = in.readLine();
        List<Word> wordsToLearn = new ArrayList<>();

        try {
            if ("1".equals(typeChoice)) {
                // 从系统词书选择
                List<SystemWordBook> systemBooks = systemBookService.getAllSystemBooks();
                out.println("\n请选择系统词书ID：");
                for (SystemWordBook book : systemBooks) {
                    out.println("ID: " + book.getId() + " - " + book.getName());
                }
                int bookId = Integer.parseInt(in.readLine());
                wordsToLearn = systemBookService.getWordsByBookId(bookId);
            } else if ("2".equals(typeChoice)) {
                // 从用户单词本选择
                List<UserWordBook> userBooks = userBookService.getUserWordBooks(loginUser.getId());
                out.println("\n请选择我的单词本ID：");
                for (UserWordBook book : userBooks) {
                    out.println("ID: " + book.getId() + " - " + book.getName());
                }
                int bookId = Integer.parseInt(in.readLine());
                wordsToLearn = userBookService.getWordsFromBook(bookId,loginUser.getId());
            } else {
                out.println("无效选择");
                return;
            }

            // 过滤已学习过的单词（查询study_record中已存在的单词ID）
            List<Integer> learnedWordIds = getLearnedWordIds(loginUser.getId());
            List<Word> newWords = wordsToLearn.stream()
                    .filter(word -> !learnedWordIds.contains(word.getId()))
                    .limit(10) // 每次学习10个新单词
                    .collect(Collectors.toList());

            if (newWords.isEmpty()) {
                out.println("该词书中没有未学习的新单词！");
                return;
            }

            // 逐个学习单词
            StudyRecordDAO recordDAO = new StudyRecordDAO();
            for (Word word : newWords) {
                out.println("\n--- 新单词 ---");
                out.println(word); // 展示单词详情（toString已实现）
                out.println("请输入对该单词的熟悉度（0-5，0=陌生，5=掌握）：");
                int familiarity = Integer.parseInt(in.readLine());
                // 验证输入范围
                if (familiarity < 0 || familiarity > 5) {
                    out.println("输入无效，默认按0处理");
                    familiarity = 0;
                }
                // 记录学习记录（首次学习，会插入study_record表）
                recordDAO.updateStudyRecord(loginUser.getId(), word.getId(), familiarity);
                out.println("已记录学习进度！");
            }
            out.println("\n=== 本次学习结束 ===");
        } catch (Exception e) {
            out.println("学习失败：" + e.getMessage());
        }
    } // 辅助方法：获取用户已学习过的单词ID
    private List<Integer> getLearnedWordIds(int userId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Integer> wordIds = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT word_id FROM study_record WHERE user_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                wordIds.add(rs.getInt("word_id"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
//            DBUtil.close(conn, pstmt, rs);
        }
        return wordIds;
    }


}